package com.weizhu.swufer.core.util;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;

public class BeanUtil {

    private final static ConcurrentMap<Class<?>, Object> classInstances = new ConcurrentHashMap<>(64);


    public static <T> T createInstance(Class<T> clazz){
        try {
            return doCreateNoArgsBean(clazz);
        }catch (ReflectiveOperationException e){
            throw new IllegalStateException("can create instance for " + clazz.getName() + ",ex:"
                    + e.getMessage());
        }
    }

    public synchronized static <T> T createSingletonInstance(Class<T> clazz) {
        try {
            T instance = (T) classInstances.get(clazz);
            if (instance == null){
                instance = doCreateNoArgsBean(clazz);
                classInstances.putIfAbsent(clazz,instance);
            }
            return instance;
        }catch (ReflectiveOperationException e){
            throw new IllegalStateException("can create instance for " + clazz.getName() + ",ex:"
            + e.getMessage());
        }

    }

    private static <T> T doCreateNoArgsBean(Class<T> clazz) throws ReflectiveOperationException{
        Constructor<T> defaultConstructor = null;
        try {
            defaultConstructor = clazz.getConstructor();
        } catch (NoSuchMethodException ignored) {

        }
        return (T) defaultConstructor.newInstance();
    }

}
